import fs from 'fs-extra';

export class GradleUtil {
    static async modifyGradleProperty(propertyFile: string, propertyName: string, replacer: (oldValue: string | null) => string | null): Promise<void> {
        if (!fs.existsSync(propertyFile)) {
            return;
        }

        const content = await fs.readFile(propertyFile, 'utf8');
        const lines = content.split(/\r?\n+/);
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i];
            const idx = line.indexOf('=');
            if (idx >= 0) {
                const key = line.substring(0, idx).trim();
                if (key == propertyName) {
                    const oldValue = line.substring(idx + 1).trim();
                    const newValue = replacer(oldValue);
                    if (newValue != null) {
                        lines[i] = `${key}=${newValue}`;
                    } else {
                        lines.splice(i, 1);
                    }
                    await fs.writeFile(propertyFile, lines.join('\n'), 'utf8');
                    return;
                }
            }
        }
    
    }
}